<template>
  <div class="h-full">
    <n-grid x-gap="12" :cols="3">
      <n-gi>
        <n-card title="用户组" class="h-full shadow-sm rounded-16px">
          <vxe-grid
            v-bind="userGroupGridOptions"
            :row-config="{ isCurrent: true }"
            @current-change="UserGroupCurrentChangeEvent"
          ></vxe-grid>
        </n-card>
      </n-gi>
      <n-gi>
        <n-card title="用户" class="h-full shadow-sm rounded-16px">
          <n-form ref="formRef" inline :label-width="80">
            <n-form-item label="工号">
              <n-input v-model:value="searchUserId" placeholder="模糊查询" />
            </n-form-item>
            <n-form-item label="姓名" path="user.age">
              <n-input v-model:value="searchUserName" placeholder="模糊查询" />
            </n-form-item>
            <n-form-item>
              <n-button attr-type="button" @click="handleSearchClick">查询</n-button>
            </n-form-item>
          </n-form>
          <vxe-grid
            v-bind="userInfoGridOptions"
            :row-config="{ isCurrent: true }"
            @current-change="UserInfoCurrentChangeEvent"
          ></vxe-grid>
        </n-card>
      </n-gi>
      <n-gi>
        <n-card :title="operateTitle" class="h-full shadow-sm rounded-16px">
          <n-form v-show="operateTitle == '维护 — 用户组'" :label-width="80">
            <n-form-item label="用户组">
              <n-input v-model:value="currentUserGroup.userGroupName" placeholder="输入用户组名称" />
            </n-form-item>
            <n-form-item label="描述">
              <n-input v-model:value="currentUserGroup.description" placeholder="输入描述" />
            </n-form-item>
            <n-form-item label="AccessFactory">
              <n-input
                v-model:value="currentUserGroup.accessFactory"
                placeholder="输入AccessFactory"
                :disabled="true"
              />
            </n-form-item>
            <n-form-item label="Remark">
              <n-input v-model:value="currentUserGroup.accessFactory" placeholder="输入Remark" :disabled="true" />
            </n-form-item>
            <n-form-item>
              <n-space>
                <n-button attr-type="button" type="primary" @click="InsertOrUpdateUserGroup">保存</n-button>
                <n-button attr-type="button" type="error" @click="DeleteUserGroup">删除</n-button>
              </n-space>
            </n-form-item>
          </n-form>
          <n-form v-show="operateTitle == '维护 — 用户'" :label-width="80">
            <n-form-item label="ID">
              <n-input v-model:value="currentUserInfo.userId" placeholder="输入用户编号" />
            </n-form-item>
            <n-form-item label="姓名">
              <n-input v-model:value="currentUserInfo.userName" placeholder="输入姓名" />
            </n-form-item>
            <n-form-item label="密码">
              <n-input
                v-model:value="currentUserInfo.password"
                type="password"
                show-password-on="mousedown"
                placeholder="密码"
              />
            </n-form-item>
            <n-form-item label="用户组">
              <n-select v-model:value="currentUserInfo.userGroupName" :options="selectOptions" />
            </n-form-item>
            <n-form-item label="邮箱">
              <n-input v-model:value="currentUserInfo.email" placeholder="输入邮箱" />
            </n-form-item>
            <n-form-item label="电话">
              <n-input v-model:value="currentUserInfo.phoneNumber" placeholder="输入电话" />
            </n-form-item>
            <n-form-item>
              <n-space>
                <n-button attr-type="button" type="primary" @click="InsertOrUpdateUserInfo">保存</n-button>
                <n-button attr-type="button" type="error" @click="DeleteUserInfo">删除</n-button>
              </n-space>
            </n-form-item>
          </n-form>
        </n-card>
      </n-gi>
    </n-grid>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRaw } from 'vue';
import type { SelectOption } from 'naive-ui';
import { useMessage } from 'naive-ui';
import type { VxeGridProps, VxeTableEvents } from 'vxe-table';
import {
  fetchUseGroupList,
  fetchInsertOrUpdateUserGroup,
  fetchDeleteUserGroup,
  fetchUserInfoListByUserGroup,
  fetchInsertOrUpdateUserInfo,
  fetchDeleteUserInfo,
  fetchUserInfoListBySerarch
} from '@/service/api/admin';

const message = useMessage();
const operateTitle = ref('维护');
const currentUserGroup = reactive<Admin.UserGroup>({
  userGroupName: '',
  description: '',
  accessFactory: 'ALL',
  remark: 'ALL'
});
const userGroupGridOptions = reactive<VxeGridProps>({
  border: true,
  maxHeight: 600,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    { field: 'userGroupName', title: '用户组' },
    { field: 'description', title: '描述', showOverflow: true },
    { field: 'accessFactory', title: 'accessFactory' },
    { field: 'remark', title: 'remark' }
  ],
  data: []
});

const selectOptions = ref<Array<SelectOption>>([]);
const getUserGroupList = async () => {
  const result = await fetchUseGroupList();
  if (result.data) {
    userGroupGridOptions.data = result.data;
    const optionItems: Array<SelectOption> = [];
    for (let i = 0; i < result.data.length; i += 1) {
      // eslint-disable-next-line no-new-object
      const optionItem = new Object() as SelectOption;
      optionItem.label = result.data[i].userGroupName;
      optionItem.value = result.data[i].userGroupName;
      optionItems.push(optionItem);
    }
    selectOptions.value = optionItems;
  }
};
const UserGroupCurrentChangeEvent: VxeTableEvents.CurrentChange = ({ newValue }) => {
  operateTitle.value = '维护 — 用户组';
  currentUserGroup.userGroupName = toRaw(newValue).userGroupName;
  currentUserGroup.description = toRaw(newValue).description;

  // eslint-disable-next-line @typescript-eslint/no-use-before-define
  getUserInfoListByUserGroup();
};
const InsertOrUpdateUserGroup = async () => {
  if (currentUserGroup.userGroupName !== '') {
    const result = await fetchInsertOrUpdateUserGroup(currentUserGroup);
    if (result.data) message.success('处理成功！');
    getUserGroupList();
  }
};
const DeleteUserGroup = async () => {
  if (currentUserGroup.userGroupName !== '') {
    const result = await fetchDeleteUserGroup(currentUserGroup);
    if (result.data) message.success('处理成功！');
    getUserGroupList();
  }
};
/** UserGroup End */

/** UserInfo Start */
const searchUserId = ref('');
const searchUserName = ref('');
const currentUserInfo = reactive<Admin.UserInfo>({
  userId: '',
  userName: '',
  userGroupName: '',
  password: '',
  email: '',
  departMent: '',
  remark: '',
  phoneNumber: '',
  receiveFlag: 'Y',
  factoryName: 'JWT'
});

const userInfoGridOptions = reactive<VxeGridProps>({
  border: true,
  maxHeight: 600,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'userId',
      title: '账号',
      sortable: true,
      filters: [{ data: null }],
      filterRender: { name: 'FilterInput' }
    },
    { field: 'userName', title: '姓名', width: 80 },
    { field: 'userGroupName', title: '用户组', width: 110 },
    { field: 'email', title: '邮箱', showOverflow: true },
    { field: 'phoneNumber', title: '电话', showOverflow: true }
  ],
  data: []
});

const getUserInfoListByUserGroup = async () => {
  const result = await fetchUserInfoListByUserGroup(currentUserGroup.userGroupName);
  if (result.data) userInfoGridOptions.data = result.data;
};

const handleSearchClick = async () => {
  const result = await fetchUserInfoListBySerarch(searchUserId.value, searchUserName.value);
  if (result.data) userInfoGridOptions.data = result.data;
};
const UserInfoCurrentChangeEvent: VxeTableEvents.CurrentChange = ({ newValue }) => {
  operateTitle.value = '维护 — 用户';
  currentUserInfo.userId = toRaw(newValue).userId;
  currentUserInfo.userName = toRaw(newValue).userName;
  currentUserInfo.password = toRaw(newValue).password;
  currentUserInfo.userGroupName = toRaw(newValue).userGroupName;
  currentUserInfo.email = toRaw(newValue).email;
  currentUserInfo.phoneNumber = toRaw(newValue).phoneNumber;
};
const InsertOrUpdateUserInfo = async () => {
  if (currentUserInfo.userId !== '') {
    const result = await fetchInsertOrUpdateUserInfo(currentUserInfo);
    if (result.data) message.success('处理成功！');
    getUserInfoListByUserGroup();
  }
};
const DeleteUserInfo = async () => {
  if (currentUserInfo.userId !== '') {
    const result = await fetchDeleteUserInfo(currentUserInfo);
    if (result.data) message.success('处理成功！');
    getUserInfoListByUserGroup();
  }
};
onMounted(() => {
  getUserGroupList();
});
</script>
